package cn.ibizlab.eam.core.extensions.service;

import cn.ibizlab.eam.core.eam_core.domain.EMStock;
import cn.ibizlab.eam.core.eam_core.service.IEMStockService;
import cn.ibizlab.eam.core.eam_core.service.impl.EMItemPRtnServiceImpl;
import cn.ibizlab.eam.core.util.helper.Aops;
import cn.ibizlab.eam.util.dict.StaticDict;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.eam.core.eam_core.domain.EMItemPRtn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Primary;


/**
 * 实体[还料单] 自定义服务对象
 */
@Slf4j
@Primary
@Service("EMItemPRtnExService")
public class EMItemPRtnExService extends EMItemPRtnServiceImpl {

    @Autowired
    private IEMStockService emstockService;

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    /**
     * 自定义行为[Confirm]用户扩展
     * @param et
     * @return
     */
    @Override
    @Transactional
    public EMItemPRtn confirm(EMItemPRtn et) {
        et = this.get(et.getEmitemprtnid());

        // 首先根据物品id,仓库id,库位id以及批次在库存表里面查找有没有该物品的库存记录
        String itemID = et.getItemid(); // 物品id
        String storeID = et.getStoreid();// 仓库id
        String storePartId = et.getStorepartid(); // 库位id
        String batCode = et.getBatcode(); // 批次

        EMStock query = new EMStock();
        query.setItemid(itemID);
        query.setStoreid(storeID);
        query.setStorepartid(storePartId);
        query.setBatcode(batCode);
        EMStock emStock = emstockService.getOne(Wrappers.query(query));

        if (null==emStock) {
            // 还料单相关物品判断如果没有库存，则在库存中新增一条数据，库存量为还料单数量，
            emStock = new EMStock();
            emStock.setItemid(itemID); // 物品id
            emStock.setStoreid(storeID);// 仓库id
            emStock.setStorepartid(storePartId); // 库位id
            emStock.setBatcode(batCode); // 批次
            emstockService.save(emStock);
        } else {
            // 如果已有库存数据，则库存量增加还料单的数量
            // 修改EMSTOCK（库存表）中的STOCKCNT（库存数）  修改规则：EMItemPRtn（还料表）中的PSUM（实还数）+ EMSTOCK（库存表）中的STOCKCNT（库存数）
            if (null == emStock.getStockcnt()) {
                emStock.setStockcnt(et.getPsum());
            } else {
                emStock.setStockcnt(et.getPsum() + emStock.getStockcnt());
            }
            emstockService.update(emStock);
        }
        // 还料单确认
        // 还料单点击“确认”后，流程步骤WFSTEP置空，
        et.setWfstep(null);
        // 还料状态TRADESTATE变为“已确认”20，
        et.setTradestate(Integer.valueOf(StaticDict.EMTRADESTATE.ITEM_20.getValue()));
        Aops.getSelf(this).update(et);

        return super.confirm(et);
    }
}

